import wx from "weixin-js-sdk";
// import { showToast, showToast } from 'vant';
import { showToast } from 'vant'
import { useStore } from '@/store/index';
import { storeToRefs } from "pinia";

import { orderPay } from "@/api"
export default async function onPay(integralPriceId) {
  return new Promise(async (resolve, reject) => {
    const store = useStore();
    const { userInfo } = storeToRefs(store)
    const { code, data } = await orderPay({ orderType: 10, openId: userInfo.openId, integralPriceId, choosePayType: 2 });
    console.log(code, 'code')
    if (code === 200) {
      const {
        appId,
        nonceStr,
        paySign,
        signType,
        timeStamp: timestamp,
        signature,
      } = data;
      console.log({appId,
        timestamp,
        nonceStr,
        signature: signType}, '支付参数')
      wx.config({
        debug: false,
        appId,
        timestamp,
        nonceStr,
        signature: signType,
        jsApiList: ["chooseWXPay"],
      });
      wx.error(() => {
        console.log("支付错误")
        showToast("支付错误");
        reject("支付错误")
      });
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ["chooseWXPay"],
          success: () => {
            wx.chooseWXPay({
              timestamp,
              nonceStr,
              package: data.packageVal,
              signType,
              paySign,
              success: () => {
                console.log("支付成功")
                showToast("支付成功");
                resolve(data.order_no)
              },
              cancel: () => {
              console.log("你还未完成支付，请重新支付~")
                reject()
                showToast("你还未完成支付，请重新支付~");
              },
    
              fail: () => {
              console.log("支付失败")
                reject()
                showToast("支付失败");
              },
            });
          },
          fail: () => {
            console.log("取消支付")
            showToast("取消支付");
            reject()
          },
        });
      });
    } else {
      reject()
    }
  })
}

